#!/bin/bash

set -e

root=$(cd $(dirname ${0})/..; pwd)
node_modules=${root}/node_modules
src=${root}/src
third_party=${root}/third_party
tools=${root}/tools

identifier=coremltools
virtualenv=${third_party}/virtualenv/${identifier}

if [ $(which python3) ]; then
    python="python3"
else
    python="python"
fi

bold() {
    echo "$(tty -s && tput bold)$1$(tty -s && tput sgr0)" 
}

git_sync () {
    mkdir -p "${third_party}"
    if [ -d "${third_party}/${1}" ]; then
        git -C "${third_party}/${1}" fetch --quiet -p
        git -C "${third_party}/${1}" reset --quiet --hard origin/master
    else
        git -C "${third_party}" clone --quiet --recursive ${2}
    fi
}

clean() {
    bold "coreml clean"
    rm -rf ${third_party}/coremltools
}

sync() {
    bold "coreml sync"
    git_sync coremltools https://github.com/apple/coremltools.git
}

install() {
    bold "coreml install"
    [ -n "$(python3 -m pip list --format columns --disable-pip-version-check | grep -w virtualenv)" ] || ${python} -m pip install --force-reinstall --user --quiet virtualenv
    [ -d "${virtualenv}" ] || ${python} -m virtualenv --quiet -p ${python} ${virtualenv}
    source ${virtualenv}/bin/activate
    ${python} -m pip install --quiet ${third_party}/${identifier}
    deactivate
}

schema() {
    bold "coreml schema"
    ${node_modules}/protobufjs/bin/pbjs -t static-module -w closure --no-encode --no-delimited --no-comments --no-convert --no-verify --no-create --keep-case -r coreml -o ${src}/coreml-proto.js ${third_party}/${identifier}/mlmodel/format/Model.proto
    node ${tools}/update_pbjs.js array ${src}/coreml-proto.js floatValue float 2
}

convert() {
    bold "coreml convert"
    source ${virtualenv}/bin/activate
    ${python} -m pip install --quiet onnx
    ${python} -m pip install --quiet sklearn
    ${python} ${tools}/coreml-script.py convert ${1}
    deactivate
}

while [ "$#" != 0 ]; do
    command="$1" && shift
    case "${command}" in
        "clean") clean;;
        "sync") sync;;
        "install") install;;
        "schema") schema;;
        "convert") convert ${1} && shift;;
    esac
done
